package tech.aistar.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import tech.aistar.model.pojo.Result;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * 本类用来演示: 图片上传功能
 *
 * @author: success
 * @date: 2021/5/10 3:25 下午
 */
@Controller
@RequestMapping("/upload")
public class UploadController {
    @GetMapping
    public String index(){
        return "/upload/index";
    }

    @PostMapping
    public String upload(HttpServletRequest request,MultipartFile file){

        //获取imgs的路径
        //Users/admin/Documents/success/teaching/wksp/springboot-j13/src/main/webapp/imgs/
        String path = request.getServletContext().getRealPath("/imgs/");

        //处理一下文件的名称
        String filename = file.getOriginalFilename();
        filename = UUID.randomUUID().toString()+"_"+filename;

        System.out.println(filename+"====");

        //System.out.println(filename);//8aa9b07e-abf7-4288-8d81-b0d975a9e57c_xx.png

        //构建一个file实例
        //File f = new File(path+filename);
        try {
            //上传到本项目中的imgs目录
            //file.transferTo(f);

            //图片上传到nginx服务器
            File f = new File("/usr/local/nginx/html/boot/imgs/"+filename);
            file.transferTo(f);

            //DB中更新图片的名称
        } catch (IOException e) {
            e.printStackTrace();
        }

        return "/upload/index";
    }

    @PostMapping("/uploads")
    @ResponseBody
    public Result upload2(HttpServletRequest request,MultipartFile file){

        //获取imgs的路径
        //Users/admin/Documents/success/teaching/wksp/springboot-j13/src/main/webapp/imgs/
        String path = request.getServletContext().getRealPath("/imgs/");

        //处理一下文件的名称
        String filename = file.getOriginalFilename();
        filename = UUID.randomUUID().toString()+"_"+filename;

        System.out.println(filename+"====");

        //System.out.println(filename);//8aa9b07e-abf7-4288-8d81-b0d975a9e57c_xx.png

        //构建一个file实例
        //File f = new File(path+filename);
        try {
            //上传到本项目中的imgs目录
            //file.transferTo(f);

            //图片上传到nginx服务器
            File f = new File("/usr/local/nginx/html/boot/imgs/"+filename);
            file.transferTo(f);

            //DB中更新图片的名称
        } catch (IOException e) {
            e.printStackTrace();
        }

        return new Result("200","文件上传成功",filename);
    }
}
